﻿using UnityEditor;
using UnityEngine;
using System.Collections;
using System.IO;
using System.Text;
using LitJson;

public class BuildAssetBundleMenu
{
	static string GetOutputPath()
	{
		return Path.Combine (Path.Combine (Application.streamingAssetsPath, "assetbundle"), GetPlatformName ());
	}

	public static string manifestPath = Path.Combine (Application.streamingAssetsPath, "assetBundle_manifest.json");

	[MenuItem("UnityFun/打包当前平台已命名AssetBundle")]
	static public void BuildNamedAssetBundle()
	{
		string outputPath = GetOutputPath();

		if (!Directory.Exists (outputPath)) {
			Directory.CreateDirectory (outputPath);
		}

		var options = BuildAssetBundleOptions.ForceRebuildAssetBundle;

		AssetBundleManifest manifest = BuildPipeline.BuildAssetBundles(outputPath, options, EditorUserBuildSettings.activeBuildTarget);

		//通过manifest获取文件hash，资源依赖。记录下来，同步到更新服务器
		StringBuilder sb =  new StringBuilder ();
		JsonWriter jsonWriter = new JsonWriter(sb);
		jsonWriter.PrettyPrint = true;

		jsonWriter.WriteObjectStart ();
		foreach (string name in manifest.GetAllAssetBundles()) {
			jsonWriter.WritePropertyName(name);

			jsonWriter.WriteObjectStart();

			jsonWriter.WritePropertyName("hash");
			jsonWriter.Write(manifest.GetAssetBundleHash (name).ToString());

			jsonWriter.WritePropertyName("deps");
			jsonWriter.WriteArrayStart ();
			foreach (string dep in manifest.GetAllDependencies(name)) {
				jsonWriter.Write (dep);
			}
			jsonWriter.WriteArrayEnd ();

			jsonWriter.WriteObjectEnd();

		}
		jsonWriter.WriteObjectEnd ();

		var fs = new FileStream (manifestPath, FileMode.Create);
		var sw = new StreamWriter (fs);
		sw.Write (sb.ToString ());
		sw.Close ();
		fs.Close();

		//刷新Project视图
		AssetDatabase.Refresh();

	}

	public static string GetPlatformName()
	{
		switch (EditorUserBuildSettings.activeBuildTarget)
		{
		case BuildTarget.Android:
			return "android";
		case BuildTarget.iOS:
			return "iOS";
		case BuildTarget.StandaloneWindows:
		case BuildTarget.StandaloneWindows64:
			return "windows";
		case BuildTarget.StandaloneOSXIntel:
		case BuildTarget.StandaloneOSXIntel64:
		case BuildTarget.StandaloneOSXUniversal:
			return "macOS";
		default:
			return null;
		}
	}

}
